package com.kuiandjie.web;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.catalina.comet.CometEvent;
import org.apache.catalina.comet.CometProcessor;

import com.kuiandjie.entity.Employee;
import com.kuiandjie.entity.EmployeeFlow;
import com.kuiandjie.entity.Project;

public final class MsgFlowServlet extends HttpServlet implements CometProcessor{

	private static final long serialVersionUID = 1L;
	private final Map<Integer, List<EmployeeFlow>> CFMAP = new HashMap<Integer, List<EmployeeFlow>>();
	
	@Override
	public void init() throws ServletException {
		super.init();
		getServletContext().setAttribute(MsgFlowServlet.class.getName(), this);
	}
	
	@Override
	public void event(CometEvent evt) throws IOException, ServletException {
		 switch (evt.getEventType()) {
	         case BEGIN: {
				HttpServletRequest request = evt.getHttpServletRequest();
				HttpSession session = request.getSession();
				int curPid = ((Project) session.getAttribute("curp")).getId();
				int curEid = ((Employee) session.getAttribute("employee")).getId();
				if(!CFMAP.containsKey(curPid)) {
					List<EmployeeFlow> list = new ArrayList<EmployeeFlow>();
						CFMAP.put(curPid, list);
				}
				
				if("GET".equals(request.getMethod())) {
					EmployeeFlow ef = new EmployeeFlow();
					
					evt.setTimeout(10 * 60 * 1000);
					
					ef.setId(curEid);
					ef.setCe(evt);
						CFMAP.get(curPid).add(ef);
				}
	         }
		 }
	}
	
	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		HttpSession session = request.getSession();
		int curPid = ((Project) session.getAttribute("curp")).getId();
		String json = (String) request.getAttribute("msg");
		if(json != null) {
			Object obj = request.getAttribute("me");
			if(obj == null) {
				send(json,curPid);
			} else {
				int meId = (Integer) obj;
				int atId = (Integer) request.getAttribute("at");
				sendAt(json, curPid, meId, atId);
			}
			
		}
	}
	
	private void sendAt(String json, int pid, int meId, int atId) {
		List<EmployeeFlow> list = CFMAP.get(pid);
		//int count = 0;
		for(int i = 0; i < list.size(); i++) {
			EmployeeFlow ef = list.get(i);
			if(atId != 0 && (ef.getId() == meId || ef.getId() == atId)) {
				HttpServletResponse response = ef.getCe().getHttpServletResponse();
				response.setContentType("application/json;charset=UTF-8");
				response.setCharacterEncoding("UTF-8");
				response.setStatus(HttpServletResponse.SC_OK);
				try {
					PrintWriter out = response.getWriter();
					out.println(json);
					out.flush();
					out.close();
					ef.getCe().close();
				} catch (IOException e) {
					e.printStackTrace();
				} finally {
					//list.remove(i);
				}
				
				/*count++;
				if(count == 2) {
					break;
				}*/
			} else if(ef.getId() == meId) {
					HttpServletResponse response = ef.getCe().getHttpServletResponse();
					response.setContentType("application/json;charset=UTF-8");
					response.setCharacterEncoding("UTF-8");
					response.setStatus(HttpServletResponse.SC_OK);
					try {
						PrintWriter out = response.getWriter();
						out.println(json);
						out.flush();
						out.close();
						ef.getCe().close();
					} catch (IOException e) {
						e.printStackTrace();
					} finally {
						//list.remove(i);
					}
					
					/*count++;
					if(count == 1) {
						break;
					}*/
				}
			}
	}

	private void send(String json, int pid) {
		List<EmployeeFlow> list = CFMAP.get(pid);
		while(list.size() != 0) {
			EmployeeFlow ef = list.get(0);
			HttpServletResponse response = ef.getCe().getHttpServletResponse();
			response.setContentType("application/json;charset=UTF-8");
			response.setCharacterEncoding("UTF-8");
			response.setStatus(HttpServletResponse.SC_OK);
			try {
				PrintWriter out = response.getWriter();
				out.println(json);
				out.flush();
				out.close();
				ef.getCe().close();
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				list.remove(0);
			}
		}
	}

}
